package net.chengp.esload4j.db.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author chengp
 * @email E-mail:chengp@chengp.net
 * @version 创建时间：2020年9月12日 下午3:22:40 
 *
 */
@Slf4j
public class DBUtils {
	
	public static final Map<String, DataSource> connections = new ConcurrentHashMap<String, DataSource>();
	
	public static Connection getConnection(String id, String driver, String host, String port, String username, String password) {
		Connection conn = null;	
		try {
			if(connections.containsKey(id)) {
				return connections.get(id).getConnection();
			}
			String url = "jdbc:mysql://"+host+":"+port+"/?useSSL=false&useUnicode=true&serverTimezone=Asia/Shanghai";
			Map<String, Object> config = new HashMap<String, Object>();
			config.put(DruidDataSourceFactory.PROP_URL, url);
			config.put(DruidDataSourceFactory.PROP_USERNAME, username);
			config.put(DruidDataSourceFactory.PROP_PASSWORD, password);
			config.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, driver);
			DataSource ds = DruidDataSourceFactory.createDataSource(config);
			connections.put(id, ds);
			conn = ds.getConnection();
		} catch (Exception e) {
			log.error("获取连接失败!", e);
		}
		return conn;
	}

	public static void closeResource(Connection conn, PreparedStatement st) {
		try {
			if (st != null) {
				st.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public static void closeResource(Connection conn, ResultSet rs, PreparedStatement st) throws SQLException {
		try {
			if (rs != null) {
				rs.close();
			}
			if (st != null) {
				st.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
